import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import useGetStorage from "@/hooks/useGetStorage";
import FcTextInput from "@/components/FcTextInput";
import {router} from "expo-router";
import {Flex, Toast} from "@ant-design/react-native";

import {
  useGetPhoneCodeMutation,
  useReastPasswordMutation
} from "@/store/api/my/myApi";

type Props = {}

const reastPassword = (props: Props) => {
  const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [code, setCode] = useState('')
  const [phoneTiming, setPhoneTiming] = useState<any>(-1)
  const [userInfo, setUserInfo] = useState<any>({})
  
  const timer:any = useRef(null)

  const [getPhoneCodeFun] = useGetPhoneCodeMutation()
  const [reastPasswordFun] = useReastPasswordMutation()

  useEffect(() => {
    useGetStorage('userInfo').then(res => {
      setUserInfo(res.userInfo)
    })
  },[])

  const getScrollBodyInfo = ({height}) => {
    setPageScrollBodyH(height)
  }

  //获取手机验证码
  const getPhoneCode = () => {
    if(!userInfo.phone){
      Toast.info('请先绑定手机号');
      return
    }

    if(phoneTiming > 0){
      Toast.info('请' + phoneTiming + '秒后重试');
      return
    }

    let count = 60

    timer.current = setInterval(() => {
      count = count - 1
      setPhoneTiming(count)
      if(count <= 0){
        clearInterval(timer.current);
      }
    },1000)

    getPhoneCodeFun({id: userInfo.id, phone: userInfo.phone}).then(res => {})
  }

  //密码正则，至少含 大小写字母，数字，特殊字符 三种类型，长度至少8位
  const passwordReg = (value:any) =>  {
    let regex =  new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@,\'\\|\.\?:;/\\[\\]><\}\{\\\\#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@,\'\\|\.\?:;/\\[\\]><\}\{\\\\#$%^&*`~()-+=]+$)(?![0-9\W_!@,\'\\|\.\?:;/\\[\\]><\}\{\\\\#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@,\'\\|\.\?:;/\\[\\]><\}\{\\\\#$%^&*`~()-+=]{8,30}$');
    if (!regex.test(value)) {
      return false
    }

    return true
  }

  const handleSubmit = () => {
    if(!newPassword || !confirmPassword || !code){
      Toast.info('密码或者验证码不能为空！');
      return
    }

    if(!passwordReg(newPassword)){
      Toast.info('新密码必须包含大小写字母、数字、特殊字符三种以上且8-30位！');
      return
    }

    if(newPassword != confirmPassword){
      Toast.info('两次新密码不一致！');
      return
    }

    let params = {
      username: userInfo.username,
      phone: userInfo.phone,
      password: newPassword,
      smscode: code
    }
    reastPasswordFun(params).then(res => {
      Toast.info('密码重置成功')
      router.back()
    })
  }

  return (
    <PageScrollView
      isTransparentTab
      getPageScrollBodyInfo={getScrollBodyInfo}
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={'重置密码'}
        />
      }
      pageBottom={
        <Flex justify='center' style={{height: 56, backgroundColor: '#FFF'}}>
          {
            <FcButton
              onClick={() => handleSubmit()}
              type='BjJB'
              colors={newPassword && confirmPassword && code ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
              style={{width: '90%', height: 40, justifyContent: 'center'}}
              itemStyle={{borderRadius: 8, fontSize: 15}}
              textName='提交'
            />
          }
        </Flex>
      }
    >
      <View style={{height: pageScrollBodyH - 20, backgroundColor: '#FFF', borderRadius: 8, paddingHorizontal: 8, paddingVertical: 12}}>
        <Text><Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>手机号：</Text>{userInfo.phone}</Text>

        <Text style={{marginBottom: 5, marginTop: 20}}>手机验证码：</Text>
        <FcTextInput
          leftIconEle={
            <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe606;</Text>
          }
          positionEle={
            <TouchableOpacity onPress={() => getPhoneCode()}>
              <Text style={{color: '#334DB0', fontSize: 15}}>{ phoneTiming < 0 ? '获取验证码' : phoneTiming == 0 ? '重新获取' : phoneTiming + 'S' }</Text>
            </TouchableOpacity>
          }
          inputStyle={{lineHeight: 20}}
          text={code} 
          placeholder={'请输入验证码'}
          onChangeText={setCode}
          height={48}
        />

        <Text style={{marginBottom: 5, marginTop: 20}}>新密码：</Text>
        <FcTextInput type='password' 
          text={newPassword}
          placeholder={'请输入新密码'}
          onChangeText={setNewPassword}
          inputStyle={{lineHeight: 20}}
          leftIconEleStyle={{paddingRight: 6}}
          height={48}
        />
        {
          newPassword && !passwordReg(newPassword) ?
          <Text style={{color: '#FA5151', fontSize: 12}}>必须包含大小写字母、数字、特殊字符三种以上且8-30位</Text>
          : null
        }   

        <Text style={{marginBottom: 5, marginTop: 20}}>新密码确认：</Text>
        <FcTextInput type='password' 
          text={confirmPassword}
          placeholder={'请再次输入密码'}
          onChangeText={setConfirmPassword}
          inputStyle={{lineHeight: 20}}
          leftIconEleStyle={{paddingRight: 6}}
          height={48}
        />
        {
          newPassword && confirmPassword && newPassword != confirmPassword ?
          <Text style={{color: '#FA5151', fontSize: 12}}>密码不一致</Text>
          : null
        }
        
      </View>
    </PageScrollView>
  )
}

export default reastPassword

const styles = StyleSheet.create({
  
})

